<?php

redirectIfNotPermited(array(UserRole::$roleSupport, UserRole::$roleAdmin, UserRole::$roleSchoolAdmin, UserRole::$roleDistrictAdmin));

$search = getInput("search", "");
$id = getInput("id",0);
$user = new User($id);

$roleId = getInput("roleId", false);
if($roleId == UserRole::$roleAdmin && !isAdminLoggedIn() && $user->attributes->roleId != $roleId){
	echoJsonResponse(false, "", "");
}

if($id == 0){
	$uidgen = new UidGenerator();
	$_REQUEST["presenterUid"] = $uidgen->getUid();
}

if (!$_REQUEST["id"]){
	$_REQUEST["created"] = time();
}

if (isset($_REQUEST["active"])){
	$_REQUEST["active"] = true;
}
else{
	$_REQUEST["active"] = false;
}

if (isset($_REQUEST["shareWithUsers"])){
	$_REQUEST["shareWithUsers"] = true;
}
else{
	$_REQUEST["shareWithUsers"] = false;
}

if (isset($_REQUEST["extendedFeatures"])){
	$_REQUEST["extendedFeatures"] = true;
}
else{
	$_REQUEST["extendedFeatures"] = false;
}

if (isset($_REQUEST["watermark"])){
	$_REQUEST["watermark"] = true;
}
else{
	$_REQUEST["watermark"] = false;
}

if (isset($_REQUEST["admin"])){
	$_REQUEST["admin"] = true;
}
else{
	$_REQUEST["admin"] = false;
}



$_REQUEST["lang"] = getLanguage();

if (isset($_REQUEST["password"])){
	$_REQUEST["password"] = $user->getPassword($_REQUEST["password"]);
}

if (!isset($_REQUEST["institute"])){
	$_REQUEST["institute"] = $user->attributes->institute;
}

$productId = getInput("productId", 0);
if(isset($_REQUEST["productId"])){
	unset($_REQUEST["productId"]);
}

$product = null;
if (getUserLoggedIn()->attributes->roleId == UserRole::$roleSchoolAdmin){
	$product = new Product(Product::$school);
}

if($productId){
	$product = new Product($productId);
}

if($product){
	$_REQUEST["type"] = $product->attributes->name;
	$_REQUEST["sfType"] = $product->attributes->sfType;
	$_REQUEST["productId"] = $product->attributes->id;
}

if($user->insertFieldsFromRequest()){

	if(!$id){
		$presentation = new Presentation();
		$presentations = $presentation->getPresentations($user->attributes->id);
		if (count($presentations) == 0){
			$params = array("method"=> "copyPresentation", "userId" => $user->attributes->id, "presentationId" => DEMOPRESENTATIONID);
			call_rest_service_post_async(WWWROOT . "service/service.php", $params);
		}
	}

	if($product){
		$user->gotProduct($product,false);
	}

	logSuccess(langEcho("user:save:success"));
	echoJsonResponse(true, WWWROOT . "admin/users.php");
}else{
	echoJsonResponse(false, "", "");
}

?>